package com.wechat.service.impl;

import com.wechat.entity.constants.Constants;
import com.wechat.entity.dto.LoginFormDTO;
import com.wechat.entity.dto.RegisterFormDTO;
import com.wechat.entity.vo.ResponseVO;
import com.wechat.entity.vo.UserInfoVO;
import com.wechat.exception.BusinessException;
import com.wechat.redis.RedisUtils;
import com.wechat.entity.enums.ErrorEnum;
import com.wechat.service.UserInfoService;
import com.wechat.service.UserLoginService;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Service
@Validated
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取验证码
     * 返给前端
     * @return
     */
    @Override
    public ResponseVO checkCode() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100,42);//创建算数（还有其他形式的）验证码 如：2*3
        String code = captcha.text();//获取运算结果(正确的验证码)  如 6
        String checkCodeKey = UUID.randomUUID().toString();//为本次验证码生成唯一标识
        log.info("验证码是：{}",code);

        //保存验证码（）正确答案,有效期5分钟
        redisUtils.setex(Constants.REDIS_KEY_CHECK_CODE + checkCodeKey,code,Constants.REDIS_KEY_EXPIRES_FIVE_MIN);

        String checkCodeBase64 = captcha.toBase64();//获取图片的base64编码，前端使用该Base64字符串显示验证图片
        Map<String,String> map = new HashMap<>();
        map.put("checkCode",checkCodeBase64);//验证码图片
        map.put("checkCodeKey",checkCodeKey);//验证码标识

        ResponseVO responseVO = new ResponseVO();
        responseVO.setData(map);

        return responseVO;
    }

    /**
     * 注册
     * @param registerFormDTO---前端传递的参数，含用户输入的验证码
     * @return
     */
    @Override
    public ResponseVO register(RegisterFormDTO registerFormDTO) {
        String checkCode = registerFormDTO.getCheckCode();//获取用户端验证码
        try {
            //校验验证码
            if(!checkCode.equalsIgnoreCase((String)redisUtils.get(Constants.REDIS_KEY_CHECK_CODE + registerFormDTO.getCheckCodeKey()))){
                throw new BusinessException(ErrorEnum.USER_CHECK_CODE_ERROR.getMsg());
            }
            //成功，注册
            String email = registerFormDTO.getEmail();
            String nickName = registerFormDTO.getNickName();
            String password = registerFormDTO.getPassword();
            userInfoService.register(email, nickName, password);
            
            ResponseVO responseVO = new ResponseVO();
            responseVO.setStatus("success");
            responseVO.setCode(200);
            responseVO.setInfo("注册成功");
            return responseVO;

        } catch (BusinessException e) {
            ResponseVO responseVO = new ResponseVO();
            responseVO.setStatus("error");
            responseVO.setCode(e.getCode());
            responseVO.setInfo(e.getMessage());
            return responseVO;
        } finally {
            //删除验证码---验证码验证成功，或者验证码验证失败，都需要删除验证码
            redisUtils.delete(Constants.REDIS_KEY_CHECK_CODE + registerFormDTO.getCheckCodeKey());
        }

    }

    /**
     * 登录
     * @param loginFormDTO
     * @return
     */
    @Override
    public ResponseVO login(LoginFormDTO loginFormDTO) {
        //校验验证码
        try{
            String checkCode = loginFormDTO.getCheckCode();//获取验证码
            if(!checkCode.equalsIgnoreCase((String) redisUtils.get(Constants.REDIS_KEY_CHECK_CODE+loginFormDTO.getCheckCodeKey()))){
                throw new BusinessException(ErrorEnum.USER_CHECK_CODE_ERROR.getMsg());
            }
            String email = loginFormDTO.getEmail();
            String password = loginFormDTO.getPassword();
            //执行登录逻辑
            UserInfoVO userInfoVO = userInfoService.login(email, password);
            
            ResponseVO responseVO = new ResponseVO();
            responseVO.setStatus("success");
            responseVO.setCode(200);
            responseVO.setInfo("登录成功");
            responseVO.setData(userInfoVO);
            return responseVO;
        } catch (BusinessException e) {
            ResponseVO responseVO = new ResponseVO();
            responseVO.setStatus("error");
            responseVO.setCode(e.getCode());
            responseVO.setInfo(e.getMessage());
            return responseVO;
        } finally {
            redisUtils.delete(Constants.REDIS_KEY_CHECK_CODE + loginFormDTO.getCheckCodeKey());
        }
    }





}